package com.wangxiang.sys.manage.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mysql.cj.util.TimeUtil;
import com.wangxiang.common.utils.*;
import com.wangxiang.sys.manage.dao.*;
import com.wangxiang.sys.manage.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import com.wangxiang.sys.manage.service.UserService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleUserDao roleUserDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private AuthDao authDao;
    @Autowired
    private RoleAuthDao roleAuthDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserEntity> page = this.page(
                new Query<UserEntity>().getPage(params),
                new QueryWrapper<UserEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageEntity page(PageEntity pageEntity) {
        TimeUtils timeUtils = new TimeUtils();
        PageHelper.startPage(pageEntity.getPageNum(),pageEntity.getPageSize());
        List<UserEntity> userEntities = userDao.selectList(null);
        userEntities.forEach((item)->{
            if (item.getCreateTime()!=null){
                String time = timeUtils.timeChange(item.getCreateTime());
                item.setCreateTimeStr(time);
            }
            int roleId = roleUserDao.selectRoleId(item.getUserId());
            if (roleId!=0){
                item.setRoleId(roleId);
            }

        });
        PageInfo<UserEntity> pageInfo = new PageInfo<>(userEntities);
        PageGenerate pageGenerate = new PageGenerate();
        PageEntity generate = pageGenerate.generate(pageInfo);
        return generate;
    }

    @Override
    public String img(String loginNme) {
        String img = userDao.getImg(loginNme);
        return img;
    }

    @Override
    public List<UserEntity> list(int id) {
        List<UserEntity> userEntities = userDao.listEntity(id);
        return userEntities;
    }

    @Override
    public UserEntity getEntityByLoginId(String LoginId) {
        UserEntity entity = userDao.getEntity(LoginId);
        return entity;
    }

    @Override
    public int add(HashMap<String, Object> map) {
        UserEntity userEntity = new UserEntity();
        userEntity.setLoginId(map.get("loginId").toString());
        userEntity.setPassword(map.get("password").toString());
        userEntity.setEmail(map.get("email").toString());
        userEntity.setMobail(map.get("mobail").toString());
        userEntity.setImg("https://shop-wangxiang.oss-cn-chengdu.aliyuncs.com/userImage/userImage.png");
        userEntity.setStatus(0);
        userEntity.setCreareUserId(Integer.valueOf(map.get("createUserId").toString()));
        userEntity.setCreateTime(new Date());

        int insert = userDao.insert(userEntity);
        if (insert>0){
            UserEntity loginId = userDao.getEntity(map.get("loginId").toString());
            System.out.println("实体"+loginId);
            int role = roleUserDao.addEntity(loginId.getUserId(), Integer.valueOf(map.get("role").toString()));
            if (role>0){
                return 1;
            }
        }

//        System.out.println("id"+userEntity.getUserId());
        return 0;
    }

    @Override
    public int updateEntity(UserEntity userEntity) {
        String nullStr = "";
        //可更改的部分登录名，密码，邮箱，电话，role(其他表)
        UserEntity entityDB = userDao.selectById(userEntity.getUserId());
        UserEntity entity = new UserEntity();
        entity.setUserId(entityDB.getUserId());
        entity.setStatus(entityDB.getStatus());
        entity.setCreareUserId(entityDB.getCreareUserId());
        entity.setCreateTime(entityDB.getCreateTime());
        entity.setLoginId(userEntity.getLoginId());
        entity.setPassword(userEntity.getPassword());
        entity.setImg(entityDB.getImg());
        entity.setEmail(userEntity.getEmail());
        entity.setMobail(userEntity.getMobail());
        //更新用户表
        int i = userDao.updateById(entity);
        if (i>0){
//            更新角色表
//            System.out.println(entityDB.getUserId()+"/"+userEntity.getRoleId());
            int i1 = roleUserDao.updateEntity(entityDB.getUserId(), userEntity.getRoleId());
            return i1;
        }


        return 0;

    }

    @Override
    public UserEntity invalid(int userId) {
        int i = userDao.updateStatus(userId, 1);
        if (i>0){
            UserEntity entity = userDao.selectById(userId);
            return entity;
        }
        return null;
    }

    @Override
    public UserEntity recover(int userId) {
        int i = userDao.updateStatus(userId, 0);
        if (i>0){
            UserEntity entity = userDao.selectById(userId);
            return entity;
        }

        return null;
    }

    @Override
    public List<HashMap<String, Object>> userInfoMap(List<HashMap<String, Object>> maps) {
        //这里只需要查询管理员的名称权限名称 id
        maps.forEach((item)->{
            int userId = Integer.valueOf(item.get("doUserId").toString());
            UserEntity entity = userDao.selectById(userId);
            int roleId = roleUserDao.getRoleIdByUser(userId);
            RoleEntity roleEntity = roleDao.selectById(roleId);
            item.put("doShipName",entity.getLoginId());
            item.put("doshipRoleName",roleEntity.getName());
            item.put("doshipRoleId",roleId);
        });

        return maps;
    }

    @Override
    public void lineStatus(int id,int code) {
        userDao.updateLineStatus(id,code);

    }

    @Override
    public HashMap<String, Object> info(int id) {
        HashMap<String, Object> map = new HashMap<>();
        UserEntity entity = userDao.selectById(id);
        map.put("userName",entity.getLoginId());
        map.put("creatUserId",entity.getCreareUserId());
        map.put("password",entity.getPassword());
        map.put("image",entity.getImg());
        map.put("email",entity.getEmail());
        map.put("mobile",entity.getMobail());
        TimeUtils timeUtils = new TimeUtils();
        map.put("creatTime",timeUtils.timeChange(entity.getCreateTime()));
        map.put("loginTime",timeUtils.timeChange(new Date()));
        int roleIdByUser = roleUserDao.getRoleIdByUser(id);
        RoleEntity roleEntity = roleDao.selectById(roleIdByUser);
        map.put("roleId",roleIdByUser);
        map.put("roleName",roleEntity.getName());
        //权限
        List<Integer> authList = roleAuthDao.getAuthIdListByRoleId(roleIdByUser);
        ArrayList<String> auth = new ArrayList<>();
        for (Integer integer : authList) {
            AuthEntity authEntity = authDao.getEntityById(integer);
            auth.add(authEntity.getDescribe());
        }
        map.put("authList",auth);


        return map;
    }

    @Override
    public List<HashMap<String, Object>> userLineList() {
        List<HashMap<String, Object>> list = new ArrayList<>();
        List<UserEntity> userEntities = userDao.selectList(null);
        for (UserEntity userEntity : userEntities) {
            //插权限
            HashMap<String, Object> map = new HashMap<>();
            int roleIdByUser = roleUserDao.getRoleIdByUser(userEntity.getUserId());
            map.put("roleId", roleIdByUser);
            map.put("userName",userEntity.getLoginId());
            map.put("line",userEntity.getLineStatus());
            list.add(map);

        }
        return list;
    }

    @Override
    public UserEntity getEntityByUserId(int userId) {
        UserEntity entity = userDao.selectById(userId);
        return entity;
    }

    @Override
    public int updatePassword(int userId, String password) {
       int update =  userDao.updatePassword(userId,password);
        return update;
    }

    @Override
    public List<UserEntity> entityList() {
        List<UserEntity> userEntities = userDao.selectList(null);
        return userEntities;
    }

    @Override
    public int updateImage(HashMap<String, Object> map) {
        int i = userDao.updateImage(Integer.valueOf(map.get("userId").toString()), map.get("image").toString());
        return i;
    }

    @Override
    public int updateEmail(HashMap<String, Object> map) {
        int i = userDao.updateEmail(Integer.valueOf(map.get("userId").toString()), map.get("toEmail").toString());
        return i;
    }

    @Override
    public int updateMobile(HashMap<String, Object> map) {
        int i = userDao.updateMobile(Integer.valueOf(map.get("userId").toString()), map.get("mobile").toString());

        return i;
    }

    @Scheduled(cron = "0/30 * * * * ?")
    public void clearUserLineStatusTask(){
//        System.out.println("定时任务，清空状态");
        userDao.updateOutLine();
    }

}